package com.zhome.gateway.util;

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;


/**
 * 抄袭自如网关代码
 * @author cuiyh9
 * @date 2020/5/9
 */
@Slf4j
public class DesEncrypt {

    /**
     * 密钥
     */
    private static final String KEY_STRING = "vpRZ1kmU";
    /**
     * 虚拟密钥
     */
    private static final String IV_STRING = "EbpU4WtY";


    /**
     * DES加密
     * @param content
     * @return
     */
    public static String encrypt(String content) {
        try {
            if (Strings.isNullOrEmpty(content)) {
                return null;
            }
            IvParameterSpec iv = new IvParameterSpec(IV_STRING.getBytes());
            DESKeySpec dks = new DESKeySpec(KEY_STRING.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            byte[] result = cipher.doFinal(content.getBytes("utf-8"));
            return DesPlus.byteArr2HexStr(result);
        } catch (Exception e) {
            log.error("ENCRYPT ERROR:", e);
        }
        return null;
    }

    public static String decrypt(String content) {
        try {
            if (Strings.isNullOrEmpty(content)) {
                return null;
            }
            IvParameterSpec iv = new IvParameterSpec(IV_STRING.getBytes());
            DESKeySpec dks = new DESKeySpec(KEY_STRING.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            byte[] result = cipher.doFinal(DesPlus.hexStr2ByteArr(content));
            return new String(result, "utf-8");
        } catch (Exception e) {
            log.error("ENCRYPT ERROR:", e);
        }
        return null;
    }

}
